package com.jiandaoshou;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.jiandaoshou.adapter.DingDanRecyclerAdapter;
import com.jiandaoshou.base.BaseActivity;
import com.jiandaoshou.entry.DingDanDetailEntry;
import com.jiandaoshou.http.APIDefine;
import com.jiandaoshou.http.Http;
import com.jiandaoshou.utils.DividerItemDecoration;
import com.jiandaoshou.utils.JsonUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

public class DingDanShaiXuanAct extends BaseActivity implements View.OnClickListener {
    private RecyclerView mRecyclerView;
    private LinearLayoutManager LayoutManager;
    private Button Btn_StartTime;
    private Button Btn_EndTime;
    private AutoCompleteTextView Auto_TextView;
    private TextView Text_Search;
    private XRefreshView xRefreshView;
    private String str_content, str_starttime, str_endtime;
    private ImageView Img_Clear;
    private int year, month, day;
    private String shopID;
    private int count = 10, page = 1;
    private List<DingDanDetailEntry> datas;
    private DingDanRecyclerAdapter adapter;
    private HashMap<String, String> map = new HashMap<String, String>();
    private boolean flag = true;

    @Override
    public boolean showBackLogo() {
        return true;
    }

    @Override
    protected int getContentViewRes() {
        return R.layout.activity_dingdanshaixuan;
    }

    @Override
    protected String getTitleText() {
        return "订单筛选";
    }

    @Override
    public void init() {
        Auto_TextView = (AutoCompleteTextView) findViewById(R.id.auto_textview);
        mRecyclerView = $(R.id.reycler_shaixuandingdan);
        Btn_StartTime = $(R.id.btn_starttime);
        Btn_EndTime = $(R.id.btn_endtime);
        Text_Search = $(R.id.text_search);
        xRefreshView = $(R.id.shaixuan_refresh);
        Img_Clear = $(R.id.img_clear);
        //获取shopID
        shopID = getIntent().getStringExtra("shopId");
        datas = new ArrayList<DingDanDetailEntry>();
        //设置布局管理器
        LayoutManager = new LinearLayoutManager(this);
        LayoutManager.setOrientation(OrientationHelper.VERTICAL);
        mRecyclerView.setLayoutManager(LayoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        //设置增加或删除条目的动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setHasFixedSize(true);
        adapter = new DingDanRecyclerAdapter(this, datas);
        mRecyclerView.setAdapter(adapter);

        adapter.setOnItemListener(new DingDanRecyclerAdapter.OnItemListener() {
            @Override
            public void OnClickListener(int pos, View view) {
                Intent intent=new Intent(DingDanShaiXuanAct.this,JinRiDingDetailAct.class);
                intent.putExtra("OrderID",datas.get(pos).getStrOrderID());
                intent.putExtra("payMode",datas.get(pos).getStrPaymentMode());
                intent.putExtra("aount",datas.get(pos).getnTradingAmount());
                intent.putExtra("time",datas.get(pos).getDtTransactionTime());
                startActivity(intent);
            }
        });

        xRefreshView.setMoveForHorizontal(true);
        Text_Search.setOnClickListener(this);
        Btn_StartTime.setOnClickListener(this);
        Btn_EndTime.setOnClickListener(this);
        Img_Clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Auto_TextView.setText("");
            }
        });
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setAutoLoadMore(true);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                GetData(page, map, 2);
            }

            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                datas.clear();
                if (map == null) {
                    xRefreshView.stopRefresh();
                    return;
                }
                GetData(page, map, 1);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_search:
                //搜索内容
                datas.clear();
                str_content = Auto_TextView.getText().toString();
                str_endtime = Btn_EndTime.getText().toString().equals("结束时间")?null:Btn_EndTime.getText().toString();
                str_starttime = Btn_StartTime.getText().toString().equals("开始时间")?null:Btn_StartTime.getText().toString();

                if (TextUtils.isEmpty(str_starttime)) {
                    Toast.makeText(this, "请选择开始时间", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(str_endtime)) {
                    Toast.makeText(this, "请选择结束时间", Toast.LENGTH_SHORT).show();
                    return;
                }

                map = new HashMap<>();
                map.put("strEndTime", str_endtime);
                map.put("strBeginTime", str_starttime);
                map.put("strShopID", shopID);
                map.put("strPayMode", "");
                map.put("order", "desc");
                map.put("strShopSonName", str_content);
                map.put("sort", "dtTransactionTime");
                map.put("rows", count + "");
                map.put("page", page + "");
                GetData(page, map, 0);
                break;
            case R.id.btn_starttime:
                ShowDialog(Btn_StartTime);
                break;
            case R.id.btn_endtime:
                ShowDialog(Btn_EndTime);
                break;
        }
    }

    private void ShowDialog(final Button btn) {
        //获取当前年月日
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                DingDanShaiXuanAct.this.year = year;
                DingDanShaiXuanAct.this.month = monthOfYear + 1;
                DingDanShaiXuanAct.this.day = dayOfMonth + 1;
                btn.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
    }

    //网络请求
    private void GetData(int page, HashMap<String, String> map, final int r_type) {
        map.put("page", page + "");
        //获取网络请求的数据
        Http.post(APIDefine.TF_Interface_GetOrderMsg, map, new Http.HttpCallBack() {
            @Override
            public void onHttpSuccess(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    JSONArray array = (JSONArray) object.get("OrderList");
                    if (array.length() == 0) {
                        return;
                    }
                    DingDanDetailEntry entry;
                    for (int i = 0; i < array.length(); i++) {
                        entry = JsonUtil.parser.fromJson(array.get(i).toString(), DingDanDetailEntry.class);
                        datas.add(entry);
                    }
                    if (array.length() < 10) {
                        xRefreshView.setLoadComplete(true);
//                        xRefreshView.stopLoadMore();
                    } else {
                        xRefreshView.setLoadComplete(false);
                    }
                    if (r_type == 1) {
                        xRefreshView.stopRefresh();
                    } else {
                        xRefreshView.stopLoadMore();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
